<template>
  <!-- 这是登录页面 -->
  <!-- 模态框 -->
  <div class="modal">
    <!-- 遮罩层 -->
    <div class="mask" @click="changeIsShowLoginModal(false)"></div>
    <!-- 登录框 -->
    <div class="loginbox">
      <div class="close" @click="changeIsShowLoginModal(false)"></div>

      <section class="nav">
        <!-- 点击手机号时就显示,同时微信登录隐藏  动态 添加样式-->
        <a href="#" :class="{ active: isShowPhone }" @click="isShowPhone = true"
          >手机号验证</a
        >|
        <a href="#" :class="{ active: !isShowPhone }" @click="QRshow">
          微信扫码登录</a
        >
      </section>
      <div class="content">
        <!-- 手机号登录 -->
        <!--  -->
        <div class="phoneLogin" v-show="isShowPhone">
          <div class="row">
            <input
              type="text"
              placeholder="请输入手机号"
              class="ipt"
              v-model="phoneNumber"
            />
          </div>
          <div class="row">
            <!--  :accuracy	="200"  精确值,默认是5,超过5,表示200以内,不那么精准也可以通过验证 -->
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
              :imgs="arr"
              :accuracy="200"
            ></slide-verify>
          </div>
          <div class="row">
            <input
              type="text"
              placeholder="请输入短信验证码"
              class="ipt"
              v-model="code"
            />
            <!-- 给获取验证码添加一个方法 getCode-->
            <!-- <button class="btncode" @click="getCode">
              获取验证码{{ count }} -->
            <!-- </button> -->
            <button v-show="!isShowCount" class="btncode" @click="getCode">
              获取验证码
            </button>
            <button v-show="isShowCount" class="btncode">
              {{ count + "s" }}
            </button>
          </div>
          <div class="row">
            <button class="btnlogin" @click="submitFn">登录</button>
          </div>
        </div>
        <!-- 微信扫码登录 -->
        <!-- 显示微信二维码 步骤二: 提供一个显示二维码的容器 取一个id值 -->
        <div class="qrLogin" v-show="!isShowPhone" id="weixin">
          微信扫码登录
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// 引入
import { mapMutations, mapActions } from "vuex";
import {
  SendSMSAPI,
  PhoneReginAPI,
  BandingAPI,
  UserProdilesAPI,
} from "@/request/api";
import { validatePhoneNumber } from "@/utils";
export default {
  data() {
    return {
      isShowPhone: true,
      msg: "向右滑动",
      arr: [
        require("../assets/img/integral-01.9386d4bf.png"),
        require("../assets/img/integral-04.afadcbdf.png"),
        require("../assets/img/dongtian.jpg"),
      ],
      //手机号码
      phoneNumber: "",
      //倒计时数字
      count: 10,
      //是否显示倒计时
      isShowCount: false,
      //验证码
      code: "",
    };
  },
  methods: {
    ...mapMutations({
      // 改变修改方法
      changeIsShowLoginModal: "ShowModal/changeIsShowLoginModal",
      // changeIsLogined   changeIsLogined
      changeIsLogined: "loginStatus/changeIsLogined",
      asyncChangeIsShowToast: "showToast/asyncChangeIsShowToast",
    }),
    // ..............
    ...mapActions({
      // 登录模态框
      asyncChangeIsShowToast: "showToast/asyncChangeIsShowToast",
      asyncChangeUserInfo: "userInfo/asyncChangeUserInfo",
    }),
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },

    // 这里有一个倒计时
    // daojishi(){}
    daojishi() {
      //倒计时   循环定时器递减数字count
      this.isShowCount = true;
      let timer = setInterval(() => {
        this.count--;
        if (this.count <= 0) {
          // 倒计时秒数10秒          this.count = 10;
          //停止 clear
          clearInterval(timer);
          this.isShowCount = false;
        }
      }, 1000);
    },

    // 用于手机号是否正确, 不正确 提示
    // toVerify(){ return true}
    toVerify() {
      //1. 判断手机号是否正确,不正确 提示
      if (!validatePhoneNumber(this.phoneNumber)) {
        // alert("请输入正确的手机号码")
        // 替换成显示Toast组件;
        // this.changeIsShowToast(true);
        // setInterval(() => {
        //   this.changeIsShowToast({
        //     isshow: true,
        //     msg: "请输入正确的手机号码",
        //     type: "success",
        //   });
        //   setTimeout(() => {
        //     this.changeIsShowToast({
        //       isshow: false,
        //     });
        //   });
        // }, 1500);
        this.asyncChangeIsShowToast({
          isshow: true,
          msg: "请输入正确的手机号码",
          type: "success",
        });
        return;
      }
      //2. 滑块验证码不正确 提示
      if (this.msg == "再试一次" || this.msg == "向右滑动") {
        alert("请滑动滑块验证码!");
        this.asyncChangeIsShowToast({
          isshow: true,
          msg: "请输入正确的手机号码",
          type: "success",
        });
        return;
      }
      //函数默认返回undefined
      return true;
    },

    // 获取验证码
    //获取验证码
    async getCode() {
      //  1.判断手机是否正确,不正确就提示
      // let reg=/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      // if(!reg.test(this.phoneNumber)){
      //   alert('请滑动滑块验证码')
      //   return;
      // }
      // 2. 滑块验证码不正确 ,提示 需要滑动滑块验证码
      //  if(this.msg=="再试一次" || this.msg=="向右滑动"){
      //         alert('请滑动滑块验证码')
      //         // 阻止继续执行
      //         return
      //       }
      let flag = this.toVerify();
      // console.log(flag);
      if (!flag) return; //不通过时不往下执行...
      //3. 获取验证码--60s倒计时功能
      //获取验证码 --  发请求
      let res = await SendSMSAPI({
        phone: this.phoneNumber,
      });
      console.log("发送短信验证码res:", res);

      if (!res) return;
      alert("发送成功");
      //调用倒计时方法
      this.daojishi();
    },

    // ...........................

    async submitFn() {
      // 判断: 如果当前msg 是再试一次  or "向右滑动" 则弹出提示框
      // 添加登录的内容 ,1.手机号不正确提示 2. 滑块不正确
      // if (!this.toVerity()) return;
      if (!this.toVerify()) return;
      //3. 短信验证码不正确提示
      if (this.code.trim() == "") {
        alert("请输入短信验证码!");
        return;
      }
      // uuid

      //4. 发起手机号验证请求
      let uuid = localStorage.getItem("uuid");
      let res = null; //BandingAPI
      if (uuid) {
        res = await BandingAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
          uuid,
        });
      } else {
        res = await PhoneReginAPI({
          verifyCode: this.code,
          phone: this.phoneNumber,
        });
      }

      if (!res) return;
      alert("登录成功!");
      // 2.存储token  obj['a']  obj.a
      localStorage.setItem("x-auth-token", res["x-auth-token"]);
      // 3.关闭登录模态框
      this.changeIsShowLoginModal(false);
      // 4. topbar 中登录状态的切换 (修改vuex 中islogined为ture)
      this.changeIsLogined(true);

      // 绑定1 清除code
      uuid && this.$router.push(this.$route.path);
      // 绑定1 删除 uuid
      localStorage.removeItem("uuid");

      // 获取用户信息并修改vuex 里面的数据
      this.asyncChangeUserInfo();

      /*
      1. 布局一个购物车按钮
      2. vuex 中loginStatus 存储一个状态isLogined (是否登录的状态)
      store
          loginStatus
              index.js
      3. 根据isLogined 来控制购物车按钮是否显示
      本地有token isLogined 则为true ,本地无token 则为false
     */

      this.changeIsLogined(true);
      // this.changeIsLogined(true);
    },

    QRshow() {
      this.isShowPhone = false;
      // 步骤三:申请微信登录二维码
      let _this = this;
      new WxLogin({
        id: "weixin",
        appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
        scope: "snsapi_login",
        // 扫码成功后重定向的接口
        redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
        // state填写编码后的url
        state: encodeURIComponent(
          // 这个是根据自己的路径反馈的  如果是8081  这里也是要修改成8081
          window.btoa("http://127.0.0.1:8080" + _this.$route.path)
        ),
        // 调用样式文件
        href: "data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlLA0KLmltcG93ZXJCb3ggLmluZm8gew0KICBkaXNwbGF5OiBub25lOw0KfQ0KLmltcG93ZXJCb3ggcXJjb2RlIHsNCiAgbWFyZ2luLXRvcDogMjBweDsNCn0NCg==",
      });
    },
  },
};
</script>
<style lang="less" scoped>
.modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
  }
  .loginbox {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    width: 555px;
    height: 423px;
    margin: auto;
    background: url(../assets/img/login-box-bg.png);
    .close {
      position: absolute;
      top: 18px;
      right: 60px;
      width: 30px;
      height: 30px;
      background: url(../assets/img/close.png) no-repeat;
    }
    .nav {
      padding-top: 50px;
      text-align: center;
      a {
        text-decoration: none;
        color: gray;
        margin: 10px auto;
        &.active {
          color: black;
        }
      }
    }
    .content {
      width: 355px;
      height: 300px;
      margin: 10px auto 0;

      // 内容的样式  手机登录的 样式
      .phoneLogin {
        .row {
          display: flex;
          margin-bottom: 20px;
          .ipt {
            height: 50px;
            flex: 1;
            text-indent: 1em;
            outline: none;
          }
          .btncode {
            background-color: #0a328e;
            color: #fff;
            margin-left: 10px;
            width: 86px;
          }
          .btnlogin {
            background-color: #0a328e;
            color: #fff;
            width: 100%;
            height: 50px;
            outline: none;
          }
        }
      }
      .qrLogin {
        text-align: center;
      }
    }
  }
}
// 滑块验证码---子组件
/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
</style>
